﻿using System.Windows;
using System.Windows.Media;
using DCT.ViewModel;

namespace DCT.View
{
    public class TrackSegmentView : DeviceBaseView
    {
        #region Constructor

        public TrackSegmentView()
            : base()
        {
        }
                     
        #endregion // Constructor

        #region Fields

        TrackSegmentViewModel _tsViewModel;

        #endregion // Fields

        #region Methods

        public override void UpdateVisual()
        {            
            if (_tsViewModel.TSViewModelType == TrackSegmentViewModelType.Start)
            {
                base.UpdateVisual();

                if (_deviceVisual.Children.Count > 0)
                {
                    _deviceVisual.Children.RemoveAt(0);
                }
                

                Point tsStartPoint = new Point((this.Width + 1) / 2, (this.Height + 1) / 2);
                Point tsEndPoint = new Point(_tsViewModel.AnotherTSViewModel.PositionPoint.X - _tsViewModel.PositionPoint.X + tsStartPoint.X,
                                                _tsViewModel.AnotherTSViewModel.PositionPoint.Y - _tsViewModel.PositionPoint.Y + tsStartPoint.Y);

                DrawingVisual drawingVisual = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                GeometryGroup geometryGroup = new GeometryGroup();
                geometryGroup.Children.Add(new LineGeometry(tsStartPoint, tsEndPoint));
                //geometryGroup.Children.Add(new LineGeometry(tsEndPoint, new Point(100,100)));
                drawingContext.DrawDrawing(new GeometryDrawing(Brushes.Gray,
                                                               new Pen(Brushes.Gray, 5),
                                                               geometryGroup));
                drawingContext.Close();

                _deviceVisual.Children.Add(drawingVisual);
            }
            else
            {
                if (_tsViewModel.AnotherTSViewModel != null)
                {
                    _tsViewModel.AnotherTSViewModel.UpdateVisual();
                }
            }
        }

        protected override void DeviceView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            base.DeviceView_DataContextChanged(sender, e);

            if (e.NewValue is TrackSegmentViewModel)
            {
                _tsViewModel = e.NewValue as TrackSegmentViewModel;
                _tsViewModel.UpdateVisual += UpdateVisual;
            }           
        }

        #endregion // Methods
    }
}
